<template>
  <div>
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input placeholder="请输入用户名" v-model="searchStr" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="queryUserList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="success" plain @click="userAddDialog = true">创建用户</el-button>
      </el-col>
    </el-row>
    <el-table :data="userList" stripe>
      <!-- <el-table-column prop="create_time" :formatter="dateFormat" label="日期" width="180"> -->
      <!-- </el-table-column> -->
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="mg_state" label="用状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row.id,scope.row.mg_state)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" plain size="mini" @click="showUserEditDialog(scope.row)"></el-button>
          <el-button type="primary" icon="el-icon-delete" plain size="mini" @click="delUserById(scope.row.id)"></el-button>
          <el-button type="success" icon="el-icon-check" plain size="mini">记录按钮</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页模块 -->
    <!-- <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" :current-page="curPage" @current-change="currentChange">
    </el-pagination> -->
    <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" :current-page.sync="curPage" @current-change="changePage">
    </el-pagination>
    <!-- 模态框 添加用户-->
    <!-- Form -->
    <el-dialog title="添加用户" :visible.sync="userAddDialog" @close="closeUserAddDialog">
      <el-form :model="userAddForm" :rules="userAddRules" ref="userAddForm">
        <el-form-item label="用户名:" prop="username" :label-width="formLabelWidth">
          <el-input v-model="userAddForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password" :label-width="formLabelWidth">
          <el-input v-model="userAddForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" :label-width="formLabelWidth">
          <el-input v-model="userAddForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机:" :label-width="formLabelWidth">
          <el-input v-model="userAddForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 模态框 修改用户-->
    <!-- Form -->
    <el-dialog title="修改用户" :visible.sync="userEditDialog" @close="closeUserEditDialog">
      <el-form :model="userEditForm" :rules="userEditRules" ref="userEditForm">
        <el-form-item label="用户名:" :label-width="formLabelWidth">
          <el-input disabled :value="userEditForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" :label-width="formLabelWidth">
          <el-input v-model="userEditForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机:" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="userEditForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
export default {
  created() {
    this.getUserList();
  },
  data() {
    return {
      userList: [],
      pageSize: 3,
      curPage: 1,
      total: 0,
      searchStr: "",

      userAddDialog: false,
      userAddForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      formLabelWidth: "120px",
      userAddRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ]
      },
      userEditDialog: false,
      userEditForm: {
        id: -1,
        username: "",
        email: "",
        mobile: ""
      },
      userEditRules: {
        mobile: [
          { required: true },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "手机号码格式不正确",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    getUserList(curPage = 1) {
      this.$http
        .get("/users", {
          params: {
            pagenum: curPage,
            pagesize: 3,
            query: this.searchStr || ""
          },

          headers: {
            // authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          console.log(res);
          const { data, meta } = res.data;
          if (meta.status === 200) {
            this.userList = data.users;
            this.total = data.total;
            // console.log(this.total);

            this.curPage = data.pagenum;
          }
        });
    },
    dateFormat(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    /**
     * 分页点击的功能
     */
    changePage(curChange) {
      this.getUserList(curChange);
    },
    queryUserList() {
      // console.log(this.searchStr);
      this.curPage = 1;
      this.getUserList();
    },
    changeUserState(id, curState) {
      // console.log(id,":",state);
      this.$http.put(`/users/${id}/state/${curState}`).then(res => {
        console.log(res);
        const { data, meta } = res.data;
        if (meta.status === 200) {
          this.$message({
            type: "success",
            message: data.mg_state === 0 ? "禁用成功" : "启用成功",
            duration: 1000
          });
        } else {
          this.$message({
            type: "success",
            message: meta.msg,
            duration: 1000
          });
        }
      });
    },
    // 添加用户
    addUser() {
      // userAddDialog = false;
      this.$refs.userAddForm.validate(valid => {
        if (valid) {
          // this.$http.post("/users",this.userAddForm).then(res=>{
          this.$http.post("/users", this.userAddForm).then(res => {
            console.log("fang", res);
            const { meta } = res.data;
            console.log("fang2", meta);
            if (meta.status === 201) {
              this.userAddDialog = false;
              this.getUserList();
            } else {
              console.log("创建失败");
            }
          });
        } else {
          return false;
        }
      });
    },
    // 关闭对话框重置表单
    closeUserAddDialog() {
      console.log("cccc");
      this.$refs.userAddForm.resetFields();
    },
    // 关闭编辑对话框重置表单
    closeUserEditDialog() {
      console.log("bbb");
      this.$refs.userEditForm.resetFields();
    },
    // 通过Id删除用户
    delUserById(id) {
      this.$confirm("确认删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete(`users/${id}`).then(res => {
            console.log(res);
            const { meta } = res.data;
            if (meta.status === 200) {
              this.$message({
                type: "success",
                message: meta.msg
              });
              // this.getUserList();
              const index = this.userList.findIndex(res => res.id === id);
              this.userList.splice(index, 1);
              const totalPage = Math.ceil(this.userList.length / this.pageSize);
              if (this.curPage > totalPage) {
                this.getUserList(--this.curPage);
              }
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //展示编辑对话框
    showUserEditDialog(curData) {
      for (const key in curData) {
        this.userEditForm[key] = curData[key];
      }
      this.userEditDialog = true;
    },
    //编辑用户
    editUser() {
      // const index=editData.id;
      // const el=this.userList.find(res=> res.id=index);
      // console.log(el);
      // this.userEditDialog = false;
      this.$refs.userEditForm.validate(valid => {
        if (valid) {
          console.log(this.userEditForm.id);
          const { id, email, mobile } = this.userEditForm;
          this.$http
            .put(`/users/${id}`, {
              email,
              mobile
            })
            .then(res => {
              const { data, meta } = res.data;
              if(meta.status===200){
                const editUser=this.userList.find(item => item.id===id);
                editUser.email=data.email;
                editUser.mobile=data.mobile;
                this.userEditDialog=false;
              }
            });
        } else {
          console.log("验证失败");
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.breadcrumb {
  line-height: 40px;
  padding-left: 10px;
  background-color: #d4dae0;
  font-size: 18px;
}
</style>
